﻿namespace MicroCloud.Api.Systems.Areas.Admin.Controllers
{
    #region "系统设置"
    /// <summary>
    /// 系统设置
    /// </summary>
    [Description("系统设置")]
    [ModuleInfo(Code = "Settings", Name = "系统设置", OrderNo = 3, Position = "Systems", PositionName = "系统管理模块")]
    public class SettingsController : AdminApiControllerBase
    {
        #region "属性"
        #region "获取 字典数据存储"
        /// <summary>
        /// 获取 字典数据存储
        /// </summary>
        protected IKeyValueStore KeyValueStore => ServiceProvider.GetRequiredService<IKeyValueStore>();
        #endregion

        #endregion

        #region "Action方法"
        #region "读取设置"
        /// <summary>
        /// 读取设置
        /// </summary>
        /// <param name="root">设置根节点，如投票设置为Votes</param>
        /// <returns>相应节点的设置信息</returns>
        [HttpGet]
        [ModuleInfo]
        [Description("读取设置")]
        public SettingOutputDto Read(string root)
        {
            ISetting setting = root switch
            {
                "System" => KeyValueStore.GetSetting<SystemSetting>(),
                _ => throw new Exception(I18N.T("未知的设置根节点 {0}", root)),
            };
            return new SettingOutputDto(setting);
        }
        #endregion
        #region "保存指定设置项"
        /// <summary>
        /// 保存指定设置项
        /// </summary>
        /// <param name="dto">设置信息</param>
        /// <returns>JSON操作结果</returns>
        [HttpPost]
        [ModuleInfo]
        [DependOnFunction(nameof(Read))]
        [UnitOfWork]
        [Description("保存设置")]
        public async Task<AjaxResult> Update(SettingInputDto dto)
        {
            Check.NotNull(dto, nameof(dto));

            Type type = Type.GetType(dto.SettingTypeName);
            if (type == null)
            {
                return AjaxResult.Error(I18N.T("设置类型 {0} 无法找到", dto.SettingTypeName));
            }
            ISetting setting = JsonConvert.DeserializeObject(dto.SettingJson, type) as ISetting;
            OperationResult result = await KeyValueStore.SaveSetting(setting);
            if (!result.Succeeded)
            {
                return result.ToAjaxResult();
            }
            return AjaxResult.Success();
        }
        #endregion

        #region "获取应用标题"
        /// <summary>
        /// 获取应用标题
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NonFunction]
        [AllowAnonymous]
        [Description("获取应用标题")]
        public virtual string GetAppTitle()
        {
            //var key = "app.title".ToMD5();
            var key = SettingKeyConstants.SiteTitle;
            var value = KeyValueStore.KeyValues.FirstOrDefault(m => m.Key == key)?.Value;
            string appTitle = null;
            if (value is string v)
            {
                appTitle = v;
            }
            else
            {
                appTitle = value?.ToString();
            }
            if (!appTitle.IsMissing())
            {
                return I18N.T(appTitle);
            }
            return appTitle;
        }
        #endregion
        #region "设置应用标题"
        /// <summary>
        /// 设置应用标题
        /// </summary>
        /// <param name="title">应用标题</param>
        /// <returns>JSON操作结果</returns>
        [HttpPost]
        [ModuleInfo]
        [UnitOfWork]
        [Description("设置应用标题")]
        public async Task<AjaxResult> SetAppTitle(string title)
        {
            title = title.ReplaceNull();
            //var key = "app.title".ToMD5();
            var key = SettingKeyConstants.SiteTitle;
            //if (title.IsMissing())
            //{
            //    return await DeleteAppTitle();
            //}
            //else
            //{
            //    var result = await DictionaryStore.CreateOrUpdate(key, title);
            //    return result.ToAjaxResult();
            //}
            var result = await KeyValueStore.CreateOrUpdate(key, title);
            return result.ToAjaxResult();
        }
        #endregion
        #region "删除应用标题"
        /// <summary>
        /// 删除应用标题
        /// </summary>
        /// <returns>JSON操作结果</returns>
        [HttpPost]
        [ModuleInfo]
        [UnitOfWork]
        [DependOnFunction(nameof(SetAppTitle))]
        [Description("删除应用标题")]
        public async Task<AjaxResult> DeleteAppTitle()
        {
            //var key = "app.title".ToMD5();
            var key = SettingKeyConstants.SiteTitle;
            var result = await KeyValueStore.DeleteByRootKey(key);
            return result.ToAjaxResult();
        }
        #endregion

        #region "获取应用描述"
        /// <summary>
        /// 获取应用描述
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NonFunction]
        [AllowAnonymous]
        [Description("获取应用描述")]
        public virtual SiteDescription GetAppDescription()
        {
            //var key = "app.description".ToMD5();
            var key = SettingKeyConstants.SiteDescription;
            var appDescription = KeyValueStore.KeyValues.FirstOrDefault(m => m.Key == key)?.Value;
            var description = appDescription?.CastTo<SiteDescription>();
            if (description != null)
            {
                if (!description.Description.IsMissing())
                {
                    description.Description = I18N.T(description.Description);
                }
                if (!description.Subdescription.IsMissing())
                {
                    description.Subdescription = I18N.T(description.Subdescription);
                }
            }
            return description;
        }
        #endregion
        #region "设置应用描述"
        /// <summary>
        /// 设置应用描述
        /// </summary>
        /// <param name="description">网站描述</param>
        /// <returns>JSON操作结果</returns>
        [HttpPost]
        [ModuleInfo]
        [UnitOfWork]
        [Description("设置应用描述")]
        public async Task<AjaxResult> SetAppDescription(SiteDescription description)
        {
            Check.NotNull(description, nameof(description));

            //var key = "app.description".ToMD5();
            var key = SettingKeyConstants.SiteDescription;
            //if (description.Description.IsMissing() && description.Subdescription.IsMissing())
            //{
            //    return await DeleteAppDescription();
            //}
            //else
            //{
            //    var result = await DictionaryStore.CreateOrUpdate(key, description);
            //    return result.ToAjaxResult();
            //}
            var result = await KeyValueStore.CreateOrUpdate(key, description);
            return result.ToAjaxResult();
        }
        #endregion
        #region "删除应用描述"
        /// <summary>
        /// 删除应用描述
        /// </summary>
        /// <returns>JSON操作结果</returns>
        [HttpPost]
        [ModuleInfo]
        [UnitOfWork]
        [DependOnFunction(nameof(SetAppDescription))]
        [Description("删除应用描述")]
        public async Task<AjaxResult> DeleteAppDescription()
        {
            //var key = "app.description".ToMD5();
            var key = SettingKeyConstants.SiteDescription;
            var result = await KeyValueStore.DeleteByRootKey(key);
            return result.ToAjaxResult();
        }
        #endregion

        #endregion

    }
    #endregion

}

